angular.module('zmq', [])
    .factory('zmq', [
        '$q', '$rootScope', '$timeout', 'loading', 'httpService', 'ENV', 'md5', '$localStorage',
        function($q, $rootScope, $timeout, loading, httpService, ENV, md5, $localStorage) {
            var init, notification, receive, send, stop, tcp, userPushToken, appid = ENV.appId;


            document.addEventListener('deviceready', function() {
                if (ionic.Platform.platform() == 'ios') {
                    window.ZMQPlugin.getDeviceToken(function(success) {
                        userPushToken = JSON.parse(success).deviceToken;
                        alert(JSON.stringify(success));
                    }, function(error) {
                        alert(JSON.stringify(error));
                    });
                }
            });

            // 监听普通消息
            receive_messages = function() {
                document.addEventListener('zmq.messages', function(event, data, a) {
                    loading.prompt(JSON.parse(event.message).body);
                });
            };

            // 从后台获取tcp
            getTcp = function(tcp_url) {
                var q = $q.defer();
                var p_url = 'MmMessage/' + tcp_url;
                if (tcp_url == 'securitytcp' && ionic.Platform.platform() == 'ios') {
                    p_url += '?userPushToken=' + userPushToken;
                }
                httpService.query(p_url).then(function(res) {
                    if (res.code == 200) {
                        // q.resolve(res.data);
                        q.resolve({ port: "2015", ip: "139.196.211.234" });
                    }
                });
                return q.promise;
            };

            // 发送消息
            send = function(from_id, to_id, msg, type, orderId, style) {
                var data, q, send_token;
                q = $q.defer();
                if ($localStorage.freeapp_token) {
                    send_token = $localStorage.freeapp_token;
                } else {
                    send_token = ENV.token;
                }
                console.log('send_token:' + send_token);
                console.log('md5.createHash:' + md5.createHash(send_token + msg.toString()));
                var time = parseInt(new Date().getTime() / 1000, 10).toString();
                data = {
                    "from": from_id,
                    "to": to_id.toString(),
                    "type": parseInt(type) || 1,
                    "body": msg.toString(),
                    "command": "send",
                    "orderId": orderId,
                    "time": time,
                    "token": md5.createHash(send_token + time),
                    "style": style //这里是后面加的  小青 区分客服 还是医生
                };
                
                window.ZMQPlugin.send(JSON.stringify(data), function(success) {
                    console.log('clent 发送成功!');
                    q.resolve(success);
                }, function(error) {
                    console.log('clent:' + JSON.stringify(error));
                    q.reject(error);
                });
                return q.promise;
            };

            // 禁用链接
            stop = function() {
                var q = $q.defer();
                getTcp(tcp_url).then(function(url) {
                    window.ZMQPlugin.disConnect(url, function(success) {
                        console.log('clent------禁用成功!');
                        console.log('success', success);
                        q.resolve(success);
                    }, function(error) {
                        console.log('clent------禁用失败:' + JSON.stringify(error));
                        q.reject(error);
                    });
                });
                return q.promise;
            };

            // 打开通知
            notification = function(content, title) {
                $timeout(function() {
                    window.ZMQPlugin.openNotification({
                        title: title || '通知',
                        content: content || '测试通知！'
                    }, function(success) {
                        console.log('clent------通知打开成功!');
                    }, function(error) {
                        console.log('clent------通知打开失败:' + JSON.stringify(error));
                    });
                });
            };

            // zmq初始化
            init = function() {
                var platform, id, parms;
                platform = '_' + parseInt(Math.random() * 1000000);

                function f() {
                    parms = {
                        id: id.toString(),
                        token: chat_token,
                        timeout: zmq_timeout
                    };

                    getTcp(tcp_url).then(function(res_url) {
                        parms['url'] = res_url;
                        $timeout(function() {
                            console.log('parmsparmsparms', parms);
                            window.ZMQPlugin.connect(parms, function(success) {
                                console.log('clent------初始化链接成功:' + JSON.stringify(success));
                            }, function(error) {
                                console.log('clent------初始化链接失败:' + JSON.stringify(error));
                            });
                        }, 100);
                    });
                };

                function connect() {
                    stop().then(function() {
                        f();
                    }, function() { f(); });
                };

                if ($localStorage.freeapp_token) {
                    tcp_url = 'securitytcp';
                    id = $localStorage.user.userid;
                    chat_token = $localStorage.freeapp_token;
                    connect();
                } else {
                    tcp_url = 'tcp';
                    id = "YK_" + ENV.uuid + '_' + random_id;
                    chat_token = md5.createHash(ENV.token + random_id);
                    connect();
                }

            };
            return {
                init: init,
                send: send,
                receive_messages: receive_messages,
                stop: stop,
                notification: notification
            };
        }
    ]);
